package com.itany.ums.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itany.ums.constant.ResponseCodeConstant;
import com.itany.ums.dao.UserMapper;
import com.itany.ums.entity.User;
import com.itany.ums.exception.PasswordErrorException;
import com.itany.ums.exception.UserNotExistException;
import com.itany.ums.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author shixiaojun@itany
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String username, String password) throws UserNotExistException, PasswordErrorException {
        // 判断用户名是否存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        List<User> users = userMapper.selectList(wrapper);
        if(users.isEmpty()){
            throw new UserNotExistException(ResponseCodeConstant.RESPONSE_MESSAGE_USERNAME_ERROR);
        }
        // 由于用户名不能重复,因此当前获取到的集合中有且仅有一条数据
        // 取出这一条数据
        User user = users.get(0);
        // 判断密码是否正确
        if(!password.equals(user.getPassword())){
            throw new PasswordErrorException(ResponseCodeConstant.RESPONSE_MESSAGE_PASSWORD_ERROR);
        }
        return user;
    }
}
